#!/usr/bin/env bash
set -euo pipefail

echo "🚀 启动完整多Agent协作系统（使用uv）"
echo "=========================================="

# 定义所有端口和对应的Agent
declare -A AGENTS=(
    [7001]="mcp_server.py"
    [7003]="intelligent_weather_agent.py"
    [7004]="travel_agent.py"
    [7005]="restaurant_agent.py"
    [7006]="coordinator_agent.py"
    [7007]="budget_agent.py"
    [8000]="web_interface/backend/web_backend.py"
    [8080]="web_interface/frontend/index.html"
)

PORTS=(7001 7003 7004 7005 7006 7007 8000 8080)

echo "🧹 清理已占用的端口..."
for port in "${PORTS[@]}"; do
    if lsof -i :${port} >/dev/null 2>&1; then
        echo "  🔧 清理端口 ${port}"
        fuser -k ${port}/tcp || true
    fi
done
sleep 2

# 创建日志目录
LOG_DIR="logs"
mkdir -p "$LOG_DIR"

# 启动Agent函数
start_agent() {
    local name=$1
    local script=$2
    local port=$3
    
    echo "🚀 启动 ${name} (端口 ${port})..."
    
    if [[ "$script" == *"index.html"* ]]; then
        # 前端静态服务
        cd web_interface/frontend
        nohup uv run python -m http.server ${port} >"../../${LOG_DIR}/${name}.log" 2>&1 &
        cd ../..
    else
        # Python Agent
        nohup uv run python ${script} >"${LOG_DIR}/${name}.log" 2>&1 &
    fi
    
    echo $! >"${LOG_DIR}/${name}.pid"
    sleep 3
    
    # 检查端口是否启动成功
    if lsof -i :${port} >/dev/null 2>&1; then
        echo "  ✅ ${name} 启动成功 (端口 ${port})"
    else
        echo "  ❌ ${name} 启动失败 (端口 ${port})" >&2
        echo "  📋 查看日志: cat ${LOG_DIR}/${name}.log"
    fi
}

# 按顺序启动所有Agent
echo ""
echo "📋 启动Agent序列..."

start_agent "MCPServer" "mcp_server.py" 7001
start_agent "WeatherAgent" "intelligent_weather_agent.py" 7003
start_agent "TravelAgent" "travel_agent.py" 7004
start_agent "RestaurantAgent" "restaurant_agent.py" 7005
start_agent "BudgetAgent" "budget_agent.py" 7007
start_agent "CoordinatorAgent" "coordinator_agent.py" 7006
start_agent "WebBackend" "web_interface/backend/web_backend.py" 8000
start_agent "WebFrontend" "web_interface/frontend/index.html" 8080

echo ""
echo "⏳ 等待所有服务稳定..."
sleep 5

echo ""
echo "📊 服务状态检查:"
for port in "${PORTS[@]}"; do
    if lsof -i :${port} >/dev/null 2>&1; then
        echo "  ✅ 端口 ${port} 正常运行"
    else
        echo "  ❌ 端口 ${port} 未启动"
    fi
done

echo ""
echo "🎯 多Agent协作系统访问地址:"
echo "  📱 可视化界面: http://localhost:8080"
echo "  📖 API文档: http://localhost:8000/docs"
echo "  ⚙️  Agent状态: http://localhost:8000/agents/status"

echo ""
echo "🧪 测试Agent协作:"
echo "  1. 打开浏览器访问 http://localhost:8080"
echo "  2. 输入旅行需求（例如：北京3天，预算800欧，喜欢历史）"
echo "  3. 观察真实的Agent协商过程"

echo ""
echo "🔧 管理命令:"
echo "  📋 查看协商日志: ./view_logs.sh"
echo "  🛑 停止所有服务: ./stop_all_agents.sh"
echo "  📊 查看Agent状态: curl http://localhost:8000/agents/status"

echo ""
echo "📁 日志文件位置:"
for port in "${PORTS[@]}"; do
    agent_name=""
    case $port in
        7001) agent_name="MCPServer" ;;
        7003) agent_name="WeatherAgent" ;;
        7004) agent_name="TravelAgent" ;;
        7005) agent_name="RestaurantAgent" ;;
        7006) agent_name="CoordinatorAgent" ;;
        7007) agent_name="BudgetAgent" ;;
        8000) agent_name="WebBackend" ;;
        8080) agent_name="WebFrontend" ;;
    esac
    echo "  📄 ${agent_name}: ${LOG_DIR}/${agent_name}.log"
done

# 创建停止脚本
cat > stop_all_agents.sh << 'EOF'
#!/usr/bin/env bash
echo "🛑 停止所有Agent服务..."
PORTS=(7001 7003 7004 7005 7006 7007 8000 8080)
for port in "${PORTS[@]}"; do
    if lsof -i :${port} >/dev/null 2>&1; then
        echo "  🔧 停止端口 ${port} 上的服务"
        fuser -k ${port}/tcp || true
    fi
done
echo "✅ 所有服务已停止"
EOF
chmod +x stop_all_agents.sh

echo ""
echo "🚀 多Agent协作系统启动完成！"
echo "💡 Agent间协作特性:"
echo "  🤝 WeatherAgent ↔ BudgetAgent: 天气对预算的影响协商"
echo "  🎯 BudgetAgent → TravelAgent: 预算约束下的景点选择"
echo "  ⚖️  CoordinatorAgent: 统一协调和冲突解决"
echo "  📊 实时协商过程展示在前端界面"

echo ""
echo "🔄 系统正在运行中... (按 Ctrl+C 可查看实时状态)"

# 陷阱处理：用户按Ctrl+C时停止所有服务
trap 'echo ""; echo "🛑 用户请求停止，正在关闭所有服务..."; ./stop_all_agents.sh; exit 0' INT

# 实时状态监控
while true; do
    sleep 30
    echo ""
    echo "📊 系统状态更新 ($(date '+%H:%M:%S')):"
    running_count=0
    for port in "${PORTS[@]}"; do
        if lsof -i :${port} >/dev/null 2>&1; then
            echo -n "  ✅"
            ((running_count++))
        else
            echo -n "  ❌"
        fi
        echo " ${port}"
    done
    echo "  📈 运行中: ${running_count}/${#PORTS[@]} 个服务"
    
    if [ ${running_count} -eq ${#PORTS[@]} ]; then
        echo "  🎉 所有服务正常运行"
    else
        echo "  ⚠️  部分服务异常，请检查日志"
    fi
done
